<template>
  <div>
    <site-nav />
    <div class="head-item">
      <head-item />
    </div>
    <div class="content">
      <div class="container">
        <div class="header-container">
          <div class="title">修改信息</div>
          <div class="approval-details">
            预选单来源：<span v-text="formatRemark(mainDetail)">123456789456123</span>
          </div>
          <div class="tips">
            提示：商品的价格及运费可能会实时变化哦，看准后请及时下单。
          </div>
        </div>
        <ConsigneeInformation ref="addressList" :address="address" @setAddress="setAddress" />
        <div class="goods-info">
          <div>商品信息</div>
          <div>单价 (元)</div>
          <div>数量</div>
          <div>小计 (元)</div>
        </div>
        <div class="main-container">
          <div v-for="(store,j) in list" :key="j" class="content-item">
            <div class="monopoly-container">
              <div class="store-name">
                <img src="../../assets/images/shop.png" alt="">
                <span v-text="store.sellerName">仪器仪表专卖</span>
              </div>
              <div v-for="(repository, k) in store.repositoryVos" :key="k" class="goods-list">
                <div class="stock-name">
                  <span>
                    <img src="../../assets/images/warehouse.png" alt="" />
                    <span
                      class="stock-name-info"
                      v-text="repository.repositoryName"
                    >仓库名称</span
                    >
                  </span>
                </div>
                <div v-for="(item, m) in repository.merchandiseVos" :key="m" class="goods-item">
                  <!-- <input type="checkbox" v-model="checked" class="all-choose" @click="checkAll" /> -->
                  <!-- <input type="checkbox" /> -->

                  <img :src="item.mainImage" alt>
                  <div class="item-info">
                    <div class="name" v-text="item.childCategoryName">钢管</div>
                    <div
                      v-if="item.standardProa && item.proAVal"
                      class="mark"
                      v-text="item.standardProa + '：' + item.proAVal"
                    >标 号：外16内6.03
                    </div>
                    <div
                      v-if="item.standardProb && item.proBVal"
                      class="mark"
                      v-text="item.standardProb + '：' + item.proBVal"
                    >标 号：外16内6.03
                    </div>
                    <div
                      v-if="item.standardProc && item.proCVal"
                      class="mark"
                      v-text="item.standardProc + '：' + item.proCVal"
                    >标 号：外16内6.03
                    </div>
                    <div
                      v-if="item.standardProd && item.proDVal"
                      class="mark"
                      v-text="item.standardProd + '：' + item.proDVal"
                    >标 号：外16内6.03
                    </div>
                    <div
                      v-if="item.standardProe && item.proEVal"
                      class="mark"
                      v-text="item.standardProe + '：' + item.proEVal"
                    >标 号：外16内6.03
                    </div>
                  </div>
                  <div class="univalence" v-text="item.productPrice.toFixed(2) + '/' + item.unit">58.00</div>
                  <!-- v-model="num" 不应该绑定同一个，循环的时候传入item.xxx-->
                  <div class="numble">
                    <el-input-number
                      v-model="item.shopAmount"
                      :disabled="!invalid(item)"
                      :min="item.minBuyNum"
                      :max="item.skuNum"
                      @change="(value) => handleChange(value, j, k, m, item)"
                    />
                  </div>
                  <div class="total-price" v-text="(item.productPrice * item.shopAmount).toFixed(2)">58.00</div>
                  <div class="results-page">
                    <div class="del-roder">
                      <span @click="delOrder(item.id)">删除</span>
                    </div>
                    <div class="to-result" @click="toSearchResult(item)">
                      <i class="el-icon-s-order" />
                      <span>搜索结果页</span>
                    </div>
                  </div>
                </div>
                <div class="money-container">
                  <div class="money-details">
                    <div
                      class="total-money"
                      v-text="`${repository.merchandiseVos.length}件商品，总商品金额：￥${productPrice(repository)}`"
                    >
                      2件商品，总商品金额：￥116.00
                    </div>
                    <div class="transportation" v-text="repository.merchandiseVos[0].distance.toFixed(1) + 'km'">
                      运输里程：200.00km
                    </div>
                    <div class="transportation-money">
                      <span>运费总价：</span>
                      <span
                        class="all-money"
                        @click="toFreight(store.sellerId, store.sellerName, repository)"
                        v-text="freightPrice(store.sellerId, repository.repositoryId)"
                      >￥20.00></span>
                    </div>
                  </div>
                  <div class="total-money" v-text="'仓库合计: ' + totalPrice(store.sellerId, repository)">仓库合计：￥116.00</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="footer-container">
          <div class="btn-container">
            <div class="clear-btn" @click="clear">清除失效商品</div>
          </div>
        </div>
      </div>
    </div>
    <advantage-item />
    <guide-item />
    <friendly-link />
    <footer-item />
  </div>
</template>

<script>
import HeadItem from '../../layout/Header'
import SiteNav from '../../layout/Nav'
import AdvantageItem from '../../layout/Advantage'
import FooterItem from '../../layout/Footer'
import GuideItem from '../../layout/Guide'
import FriendlyLink from '../../layout/FriendlyLink'
import ConsigneeInformation from '../../components/ConsigneeInformation'
import { MessageBox } from 'element-ui'
import { toProductList } from '@/js/product'
import {
  getPushMainDetail,
  listProductDetail,
  freight,
  amount,
  deletes,
  deletePreOrder,
  updateAddress
} from '@/api/pre-order/pre-order-for-me'
import { FreightData } from '@/js/constant'

export default {
  name: 'CheckBudgetOrders',
  components: {
    HeadItem,
    SiteNav,
    AdvantageItem,
    FooterItem,
    GuideItem,
    FriendlyLink,
    ConsigneeInformation
  },
  data() {
    return {
      orderBatch: this.$route.query.orderBatch,
      num: 1,
      showPopUp: false,
      showMap: false,
      latitude: '',
      longitude: '',
      address: {},
      mainDetail: {},
      list: [],
      freights: [],
      isDelete: false,
      oldList: [],
      tempItem: undefined
    }
  },
  computed: {
    failureNum() {
      return this.list.reduce((prev, cur) => prev + cur.repositoryVos
        .reduce((_prev, _cur) => _prev + _cur.merchandiseVos
          .reduce((prev_, cur_) => prev_ + !this.invalid(cur_) ? 1 : 0, 0), 0), 0)
    }
  },
  created() {
    this.getMainDetail()
  },
  methods: {
    // 获取预选单详情主要数据
    getMainDetail() {
      getPushMainDetail(this.orderBatch).then(response => {
        if (response.data) {
          this.mainDetail = response.data
          const address = JSON.parse(response.data.recieveAddress)
          this.address = address
          this.$refs.addressList.chooseAddress = address
          this.getProductInfo()
        } else {
          this.isDelete = true
        }
      })
    },
    // 获取预选单商品数据
    getProductInfo() {
      listProductDetail(this.orderBatch).then(response => {
        this.list = response.data
        this.oldList = JSON.parse(JSON.stringify(response.data))
        this.list.forEach(i => {
          this.freightParam(i)
        })
      })
    },
    // 清除失效商品
    clear() {
      if (this.failureNum === 0) {
        this.$message.error('没有失效的商品')
        return
      }
      const list = []
      this.list.forEach(j => {
        j.repositoryVos.forEach(k => {
          k.merchandiseVos.forEach(m => {
            if (!this.invalid(m)) {
              list.push(m.id)
            }
          })
        })
      })
      this.delete(list, false)
    },
    // 删除接口,flag: true删除 false清除失效
    delete(ids, flag = true) {
      const halfMessage = flag ? '删除已选商品？' : '清空失效商品？'
      const title = flag ? '删除商品' : '清空失效商品'
      MessageBox.confirm('', {
        message: `确定要${halfMessage}`,
        title,
        showConfirmButton: true,
        showCancelButton: true,
        closeOnClickModal: false,
        cancelButtonClass: 'cancelButton',
        confirmButtonClass: 'confirmButton',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deletes(ids).then(res => {
          if (res.data) {
            const list = JSON.parse(JSON.stringify(this.list))
              .filter(j => {
                j.repositoryVos = j.repositoryVos.filter(k => {
                  k.merchandiseVos = k.merchandiseVos.filter(m => ids.indexOf(m.id) === -1)
                  return k.merchandiseVos.length > 0
                })
                return j.repositoryVos.length > 0
              })
            if (list.length === 0) {
              deletePreOrder(this.orderBatch).then(response => {
                if (response.data) {
                  this.$message.warning('预选单里不存在商品，该预选单已移除')
                }
              })
              this.$router.push('/choose-for-mime')
            }
            this.$message.success(`${title}成功`)
            this.getProductInfo()
          } else {
            this.$message.error(`${title}失败`)
          }
        }).catch(res => {
          this.$message.error(`${title}失败, ${res.data}`)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    freight(data) {
      freight(data).then(res => {
        if (this.tempItem) {
          const { j, k } = this.tempItem
          const sellerId = this.list[j].sellerId
          const repositoryId = this.list[j].repositoryVos[k].repositoryId
          const freights = JSON.parse(JSON.stringify(this.freights))
            .filter(i => i.sellerId !== sellerId && i.repositoryId !== repositoryId)
          this.freights = freights.concat(res.data)
        } else if (data.addressFlag) {
          this.freights = this.freights.concat(res.data)
        } else {
          this.freights = this.freights.concat(res.data)
        }
      }).catch(res => {
      })
    },
    totalPrice(sellerId, repository) {
      const price = repository.merchandiseVos.reduce((prev, cur) => prev + (this.invalid(cur) && !this.stockOut(cur) ? cur.shopAmount * cur.productPrice : 0), 0)
      if (this.freights.length === 0) {
        return price.toFixed(2)
      }
      const list = this.freights.filter(i => i.sellerId === sellerId && i.reposityId === repository.repositoryId)
      const freightPrice = list.length === 0 ? 0 : list[0].gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalFee, 0)
      return `￥${(freightPrice + price).toFixed(2)}`
    },
    freightPrice(sellerId, repositoryId) {
      if (this.freights.length === 0) {
        return '计算中'
      }
      const list = this.freights.filter(i => i.sellerId === sellerId && i.reposityId === repositoryId)
      if (list.length === 0) {
        return '￥' + Number(0).toFixed(2)
      }
      return '￥' + list[0].gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalFee, 0).toFixed(2)
    },
    freightParam(store) {
      const data = {
        sellerId: store.sellerId
      }
      const submitInfoList = []
      let flag = false
      store.repositoryVos.forEach(i => {
        const submitInfo = {
          reposityId: i.repositoryId,
          distance: i.merchandiseVos[0].distance
        }
        const spuInfoList = []
        i.merchandiseVos.forEach(j => {
          if (this.invalid(j) && !this.stockOut(j)) {
            flag = true
            spuInfoList.push({
              spuId: j.spuId,
              buyNum: j.shopAmount
            })
          }
        })
        if (spuInfoList.length > 0) {
          submitInfo.spuInfoList = spuInfoList
          submitInfoList.push(submitInfo)
        }
      })
      data.submitInfoList = submitInfoList
      if (flag) {
        this.freight(data)
      }
    },
    // 计算商品总价
    productPrice(repository) {
      return (repository.merchandiseVos.reduce((prev, cur) => prev + (this.invalid(cur) && !this.stockOut(cur) ? cur.shopAmount * cur.productPrice : 0), 0)).toFixed(2)
    },
    repositoryPrice(repository) {
      const price = repository.merchandiseVos.reduce((prev, cur) => prev + (cur.checked ? cur.shopAmount * cur.productPrice : 0), 0)
      if (this.freights.length === 0) {
        return price.toFixed(2)
      }
      let freightPrice = 0
      if (price !== 0) {
        const list = this.freights.filter(i => i.reposityId === repository.repositoryId)
        freightPrice = list.length === 0 ? 0 : list[0].gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalFee, 0)
      }
      return `￥${(freightPrice + price).toFixed(2)}`
    },
    // 查看运费详情
    toFreight(sellerId, sellerName, repository) {
      console.log('去运费详情页面')
      const spuList = []
      this.list.filter(i => i.sellerId === sellerId)[0].repositoryVos
        .filter(i => i.repositoryId === repository.repositoryId)[0]
        .merchandiseVos.forEach(i => {
          if (this.invalid(i) && !this.stockOut(i)) {
            const {
              mainImage,
              childCategoryName,
              productPrice,
              shopAmount,
              standardProa,
              standardProb,
              standardProc,
              standardProd,
              standardProe,
              proAVal,
              proBVal,
              proCVal,
              proDVal,
              proEVal,
              unit
            } = i
            const property = []
            if (standardProa && proAVal) {
              property.push({
                name: standardProa,
                value: proAVal
              })
            }
            if (standardProb && proBVal) {
              property.push({
                name: standardProb,
                value: proBVal
              })
            }
            if (standardProc && proCVal) {
              property.push({
                name: standardProc,
                value: proCVal
              })
            }
            if (standardProd && proDVal) {
              property.push({
                name: standardProd,
                value: proDVal
              })
            }
            if (standardProe && proEVal) {
              property.push({
                name: standardProe,
                value: proEVal
              })
            }
            const obj = {
              mainImg: mainImage,
              spuName: childCategoryName,
              price: productPrice,
              unit,
              buyNum: shopAmount,
              property
            }
            spuList.push(obj)
          }
        })
      if (spuList.length <= 0) {
        this.$message.error('暂无需要计算运费的商品')
        return
      }
      const gruopFeeInfoList = this.freights.filter(i => i.sellerId === sellerId && i.reposityId === repository.repositoryId)[0].gruopFeeInfoList
      const totalFee = gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalFee, 0)
      const totalWeight = gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalWeight, 0)
      const totalVolue = gruopFeeInfoList.reduce((prev, cur) => prev + cur.totalVolue, 0)
      const freightData = {
        sellerName: sellerName,
        productList: {
          spuList,
          distance: gruopFeeInfoList[0].distance,
          totalWeight,
          totalVolue,
          totalFee
        }
      }
      sessionStorage.setItem(FreightData, JSON.stringify(freightData))
      this.$router.push('/prepaid')
    },
    handleChange(value, j, k, m, item) {
      if (!value) {
        this.$message.error('数量不能为空')
        item.shopAmount = this.oldList[j].repositoryVos[k].merchandiseVos[m].shopAmount
        return
      }
      this.tempItem = {
        j,
        k,
        item
      }
      const { id, spuRepositoryId } = item
      const formData = new FormData()
      formData.append('id', id)
      formData.append('spuRepositoryId', spuRepositoryId)
      formData.append('shopAmount', value)
      formData.append('orderBatch', this.orderBatch)
      amount(formData).then(res => {
        if (res.data) {
          // item.shopAmount = shopAmount
          this.$message.success('修改成功')
          this.freightParam(this.list[j])
        } else {
          this.$message.error(res.data)
          item.shopAmount = this.oldList[j].repositoryVos[k].merchandiseVos[m].shopAmount
        }
      }).catch(res => {
        this.$message.error(`修改数量失败,${res.data}`)
        item.shopAmount = this.oldList[j].repositoryVos[k].merchandiseVos[m].shopAmount
      })
      console.log(value)
      console.log(item)
    },
    addAddress() {
      document.body.style.overflow = 'hidden'
      this.showPopUp = true
    },
    // 设置地址
    setAddress(address) {
      const path = []
      let index = 0
      const list = this.list
      list.forEach(i => {
        i.repositoryVos.forEach(j => {
          j.index = index++
          path.push(j.repositoryId)
        })
      })
      if (path.length > 0) {
        const formData = new FormData()
        if (address.id) {
          formData.append('id', address.id)
        }
        formData.append('latitude', address.latitude)
        formData.append('longitude', address.longitude)
        formData.append('receiveAddress', address.receiveAddress)
        formData.append('receiveCity', address.receiveCity)
        formData.append('receiveDistrict', address.receiveDistrict)
        formData.append('receiveProvince', address.receiveProvince)
        formData.append('receiverName', address.receiverName)
        formData.append('receiverPhone', address.receiverPhone)
        updateAddress(formData, this.orderBatch, path).then(res => {
          const data = res.data
          if (data) {
            this.$message.success('修改地址成功')
            this.address = address
            data.forEach((i, index) => {
              // eslint-disable-next-line no-labels
              ok: for (let j = 0; j < list.length; j++) {
                for (let k = 0; k < list[j].repositoryVos.length; k++) {
                  if (list[j].repositoryVos[k].index === index) {
                    delete list[j].repositoryVos[k].index
                    list[j].repositoryVos[k].merchandiseVos.forEach(m => {
                      m.distance = i
                    })
                    // eslint-disable-next-line no-labels
                    break ok
                  }
                }
              }
            })
            this.list = list
            this.freights = []
            JSON.parse(JSON.stringify(list)).forEach(i => {
              i.addressFlag = true
              this.freightParam(i)
            })
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    toSearchResult(item) {
      if (!this.invalid(item)) {
        return
      }
      const address = this.address
      const condition = {
        sortType: 0,
        childCategory: {
          id: item.childCategoryId,
          categoryUnit: item.unit,
          standardProa: item.standardProa,
          standardProb: item.standardProb,
          standardProc: item.standardProc,
          standardProd: item.standardProd,
          standardProe: item.standardProd,
          categoryName: item.childCategoryName
        },
        mainCategory: {
          id: item.mainCategoryId,
          categoryName: item.mainCategoryName
        },
        proaId: item.spuAId,
        probId: item.spuBId,
        procId: item.spuCId,
        prodId: item.spuDId,
        proeId: item.spuEId,
        address,
        info: { proa: item.proAVal, prob: item.proBVal, proc: item.proCVal, prod: item.proDVal, proe: item.proEVal },
        buyNum: item.shopAmount,
        searchRange: 50 || item.distance
      }
      toProductList(this, condition)
    },
    delOrder(id) {
      this.delete([id])
    },
    // false 失效
    invalid(item) {
      return item.status === 5 && item.brandId === item.cartBrandId &&
          item.proAId === item.spuAId && item.proBId === item.spuBId &&
          item.proCId === item.spuCId && item.proDId === item.spuDId && item.proEId === item.spuEId
    },
    // true 缺货
    stockOut(item) {
      return item.skuNum < item.minBuyNum || item.skuNum < item.shopAmount
    },
    // 格式化账户备注
    formatRemark(item) {
      if (item.remark) {
        return item.remark + '(' + item.userName + ')'
      } else {
        return item.userName
      }
    }
  }
}
</script>

<style scoped lang="scss">
  ::v-deep .head-item {
    .head {
      border-bottom: 2px solid #ff3b30ff;
    }
  }

  .content {
    background-color: #f7f7f7;
    padding-bottom: 52px;
    .container {
      .header-container {
        background-color: #fff;
        align-items: center;
        margin: 30px 0 0 0;
        .title {
          font-weight: 700;
          font-size: 16px;
          height: 57px;
          padding: 17px 0 20px 20px;
          border-bottom: 3px solid #e5e5e5ff;
        }
        .approval-details {
          padding: 15px 18px 20px 20px;
          display: flex;

          height: 55px;
          color: #3d3d3dff;
        }
      }
      .goods-info {
        margin-bottom: 10px;
        height: 55px;
        background-color: #fff;
        display: flex;
        align-items: center;
        line-height: 44px;
        div:nth-child(1) {
          margin-left: 20px;
        }
        div:nth-child(2) {
          margin-left: 702px;
        }
        div:nth-child(3) {
          margin: 0 102px;
        }
      }
      .main-container {
        // background-color: #fff;

        .content-item {
          margin-bottom: 10px;

          .monopoly-container {
            .store-name {
              padding: 0 20px;
              background-color: #fff;
              height: 47px;
              line-height: 47px;

              img {
                width: 15px;
                height: 15px;
                margin-right: 5px;
              }
            }
            .goods-list {
              background-color: #fff;
              padding: 0px 20px 0 0px;
              .stock-name {
                border-bottom: 1px solid #e5e5e5ff;
                padding-left: 20px;
                display: flex;
                padding-bottom: 11px;
                margin-bottom: 18px;
                color: #A7A7AAFF;
                img {
                  width: 15px;
                  height: 15px;
                  margin-right: 5px;
                  background-color: red;
                }
              }
              .goods-item {
                display: flex;
                align-items: center;
                // justify-content: space-between;

                padding: 0 0 15px 0;
                padding-left: 20px;
                input {
                  margin: 0 10px 0 18px;
                }
                .lose-efficacy {
                  margin: 0 2px 0 3px;
                  padding: 0 7px;
                  background-color: #a7a7aa;
                  border-radius: 2px;
                  color: #fff;
                  font-size: 11px;
                }
                img {
                  width: 83px;
                  height: 83px;
                  object-fit: cover;
                  margin-right: 30px;
                }
                .item-info {
                  height: 83px;

                  .mark {
                    font-size: 12px;
                    color: #a7a7aa;
                  }
                }
                .univalence {
                  margin-left: 380px;
                }
                .numble {
                  margin: 0 100px;
                  ::v-deep .el-input-number {
                    display: flex;
                    width: 68px;
                  }
                  ::v-deep .el-input-number__decrease {
                    width: 17px;
                    height: 17px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border-right: 1px solid #dcdfe6;
                    top: 1px;
                    left: 5px;
                  }
                  ::v-deep .el-input-number__increase {
                    width: 17px;
                    height: 17px;
                    display: flex;
                    justify-content: center;
                    top: 1px;
                    right: 5px;
                    align-items: center;
                    border-left: 1px solid #dcdfe6;
                  }
                  ::v-deep .el-input {
                    width: 60px;
                    height: 21px !important;
                    left: 4px;
                    // z-index: 100;
                  }
                  ::v-deep .el-input__inner {
                    display: flex;
                    width: 60px;
                    padding: 0;
                    justify-content: center;
                    align-items: center;
                    height: 19px !important;
                    color: #8e8e93;

                    border-radius: 0;
                  }
                  // .comment {
                  //   display: flex;
                  //   justify-content: center;
                  //   align-items: center;
                  //   width: 19px;
                  //   height: 19px;
                  //   color: #8e8e93;
                  //   border: 1px solid #f4f5f7;
                  //   background-color: #f5f7fa;
                  // }
                  // span:nth-child(2) {
                  //   width: 30px;
                  //   height: 19px;
                  //   border: 1px solid #f4f5f7;
                  //   display: flex;
                  //   justify-content: center;
                  //   align-items: center;
                  //   color: #8e8e93;
                  // }
                }

                .results-page {
                  margin-left: 60px;
                  margin-right: 0;
                  color: #6b6b6bff;
                  span {
                    margin-left: 10px;
                  }
                  .del-roder {
                    width: 90px;
                    text-align: center;
                    color: #02a9f1ff;
                    margin-bottom: 3px;
                  }
                }
                .results-page:hover {
                  cursor: pointer;
                }
              }
            }
          }
          .money-container {
            // margin-bottom: 20px;
            height: 69px;
            padding: 15px;
            display: flex;
            background-color: #fff;
            align-items: flex-end;
            justify-content: space-between;
            flex-direction: column;
            color: #6b6b6b;
            border-top: 3px solid #e5e5e5ff;
            .money-details {
              display: flex;
              .transportation {
                margin: 0 25px;
              }
              .transportation-money {
                .all-money {
                  color: #02a9f1;
                }
                .all-money:hover {
                  cursor: pointer;
                }
              }
            }
          }
        }
      }
      .footer-container {
        height: 120px;
        background-color: #fff;
        margin-top: 20px;
        display: flex;
        padding: 20px;
        flex-direction: column;
        justify-content: space-between;
        align-items: flex-end;
        .btn-container {
          display: flex;
          justify-content: center;
          align-items: center;
          .clear-btn {
            color: #fff;
            width: 110px;
            height: 37px;
            line-height: 37px;
            text-align: center;
            background-color: #209cd3;
            border-radius: 4px;
            margin-left: 30px;
          }
        }
        .tips {
        }
      }
    }
  }
</style>
